package com.mezz.bones.framework.web.util;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.JakartaServletUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.nio.charset.Charset;

@Slf4j
public class ServletUtils extends JakartaServletUtil{
  /**
   * 获取String参数
   */
  public static String getParameter(String name) {
    return getRequest().getParameter(name);
  }

  public static String getVersion(){
    String result = JakartaServletUtil.getHeader(getRequest(), "version", Charset.defaultCharset());
    return StrUtil.isNotBlank(result) ? result : "0.0.0";
  }

  public static String getUserAgent(){
    String userAgent = JakartaServletUtil.getHeader(getRequest(), "User-Agent", Charset.defaultCharset());
    return StrUtil.isNotBlank(userAgent) ? userAgent : "";
  }

  /**
   * 获取String参数
   */
  public static String getParameter(String name, String defaultValue) {
    return Convert.toStr(getRequest().getParameter(name), defaultValue);
  }

  /**
   * 获取Integer参数
   */
  public static Integer getParameterToInt(String name) {
    return Convert.toInt(getRequest().getParameter(name));
  }

  /**
   * 获取Integer参数
   */
  public static Integer getParameterToInt(String name, Integer defaultValue) {
    return Convert.toInt(getRequest().getParameter(name), defaultValue);
  }

  /**
   * 获取request
   */
  public static HttpServletRequest getRequest() {
    return getRequestAttributes().getRequest();
  }

  /**
   * 获取response
   */
  public static HttpServletResponse getResponse() {
    return getRequestAttributes().getResponse();
  }

  /**
   * 获取session
   */
  public static HttpSession getSession() {
    return getRequest().getSession();
  }

  public static ServletRequestAttributes getRequestAttributes() {
    RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
    return (ServletRequestAttributes) attributes;
  }

  /**
   * 获取ip地址
   */
  public static String fetchIp() {
    HttpServletRequest request = ServletUtils.getRequest();
    String ip = JakartaServletUtil.getClientIP(request);
    // 优化处理：检查本地 IPv6 地址，转换为 IPv4 的 127.0.0.1
    if ("0:0:0:0:0:0:0:1".equals(ip) || "::1".equals(ip)) {
      return "127.0.0.1";
    }
    return ip;
  }


  /**
   * @author mezz
   * @date 2022/6/22 17:06
   * @description 获取登录设备号
   */
  public static String getDevice(){
    HttpServletRequest request = ServletUtils.getRequest();
    String device = request.getHeader("device");
    if(StrUtil.isNotBlank(device)){
      return device.toLowerCase();
    }

    return "unknown";
  }

}
